package com.jlkf.service.impl;

import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jlkf.dao.TblIntegralSetMapper;
import com.jlkf.dao.TblMessageMapper;
import com.jlkf.dao.TblOrderMapper;
import com.jlkf.dao.TblUserMapper;
import com.jlkf.dao.TblUserPurseInfoMapper;
import com.jlkf.pojo.TblIntegralSet;
import com.jlkf.pojo.TblMessage;
import com.jlkf.pojo.TblOrder;
import com.jlkf.pojo.TblUser;
import com.jlkf.pojo.TblUserPurseInfo;
import com.jlkf.service.TblIntegralSetService;
import com.platform.server.response.response.pojo.ReturnData;
import com.platform.server.util.MD5Util;
import com.platform.server.util.RSAUtil;
import com.platform.server.util.StringTools;
import com.platform.server.util.WxpayDemoUtils;

@Service
public class TblIntegralSetServiceImpl implements TblIntegralSetService{
	@Autowired
	private TblIntegralSetMapper tblIntegralSetMapper;
	@Autowired
	private TblUserMapper tblUserMapper;
	@Autowired
	private TblOrderMapper tblOrderMapper;
	@Autowired
	private TblUserPurseInfoMapper tblUserPurseInfoMapper;
	@Autowired
	private TblMessageMapper tblMessageMapper;
	
	/**
	 * 计算积分
	 */
	@Override
	public ReturnData calculateIntegral(Double money) {
		// TODO Auto-generated method stub
		TblIntegralSet integralSet = tblIntegralSetMapper.selectByType(2);
	    int num = (int)Math.floor(money/integralSet.getMoney());
	    int integral = num*integralSet.getIntegral();
		return new ReturnData(integral,200,"所得积分");
	}

	/**
	 * 余额兑换积分
	 * @throws InvalidKeySpecException 
	 */
	@Override
	public ReturnData buyIntegral(String json) throws InvalidKeySpecException{
		// TODO Auto-generated method stub
		try {
			Map<String, Object> map = StringTools.jsonToMap(json);
			Long userId = Long.valueOf(map.get("userId").toString());
			Double payMoney = Double.valueOf(map.get("payMoney").toString());
			Integer integral = Integer.valueOf(map.get("integral").toString());
			String password = map.get("password").toString();
			
			//RSA解密
			String payWord = RSAUtil.privateDecrypt(password, RSAUtil.getPrivateKey(RSAUtil.privateKey));
			
			if(userId==null || payMoney==null || integral==null || password==null){
				return new ReturnData(500,"参数有误");
			}
			TblUser user = tblUserMapper.selectByPrimaryKey(userId);
			if(user == null){
				return new ReturnData(15,"未找到该用户信息");
			}
			String pay_password = user.getgUserPayPassword();		//用户钱包密码
			if(StringTools.isEmpty(pay_password)){
				return new ReturnData(20,"请先设置支付密码");
			}
			Double money = user.getgUserMoney();		//用户钱包金额
			if(money < payMoney){
				return new ReturnData(30,"钱包金额不足，请先充值");
			}
			
			if(!MD5Util.getMD5(payWord).equals(pay_password)){
				return new ReturnData(40,"密码错误");
			}
		
			//减少用户钱包金额
			TblUser tuser = new TblUser();
			tuser.setgId(userId);
			tuser.setgUserMoney(money - payMoney);
			tuser.setgUserIntegral(user.getgUserIntegral()+integral);
			int flag1 = tblUserMapper.updateByPrimaryKeySelective(tuser);		
			//添加会员订单
			String orderid = WxpayDemoUtils.getRandomString(16);
			TblOrder order = new TblOrder();
			order.setgOrderNo(orderid);
			order.setgCreatetime(new Date());
			order.setgOrderTotalMoney(payMoney);
			order.setgOrderPayMoney(payMoney);
			order.setgOrderStatus(1);
			order.setgVersion(3);
			order.setgOrderType(4);
			order.setgUserId(userId);
			order.setgGoodsName("购买积分");
			order.setgGoodsId("0");
			order.setgPayTime(new Date());  //购买时间
			tblOrderMapper.insertSelective(order);
			
			//新增钱包明细
			TblUserPurseInfo purseInfo = new TblUserPurseInfo();
			purseInfo.setgContent("购买积分");
			purseInfo.setgCreatetime(new Date());
			purseInfo.setgMoney(payMoney);
			purseInfo.setgStatus(2);
			purseInfo.setgTitle("购买积分");
			purseInfo.setgType(1);
			purseInfo.setgBalance(money-payMoney);
			purseInfo.setgUserid(userId);
			tblUserPurseInfoMapper.insertSelective(purseInfo);
			
			//新增积分明细
			TblUserPurseInfo purseInfo1 = new TblUserPurseInfo();
			purseInfo1.setgContent("余额兑换积分");
			purseInfo1.setgCreatetime(new Date());
			purseInfo1.setgMoney(integral.doubleValue());
			purseInfo1.setgStatus(1);
			purseInfo1.setgTitle("余额兑换");
			purseInfo1.setgType(2);
			purseInfo1.setgBalance(user.getgUserIntegral()+integral);
			purseInfo1.setgUserid(userId);
			tblUserPurseInfoMapper.insertSelective(purseInfo1);
			
			int i = new Double(purseInfo1.getgBalance()).intValue();
			TblMessage record3 = new TblMessage();
			record3.setgContent("充值"+integral+"积分,现有积分"+i);
			record3.setgTitle("积分提示");
			record3.setgType(2);
			record3.setgUserId(userId);
			record3.setgCreatetime(new Date());
			record3.setgVersion(1);
			tblMessageMapper.insertSelective(record3);
			return new ReturnData(200,"购买成功");
	    } catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new ReturnData(500,"系统错误");
		}
	}

	@Override
	public ReturnData getIntegralList(Long userId,Integer type, Integer pageNumber, Integer pageSize) {
		// TODO Auto-generated method stub
		if(userId==null){
			return new ReturnData(500,"暂无数据");
		}
		if(pageNumber==null){
			pageNumber=1;
		}
		if(pageSize==null){
			pageSize=10;
		}
		Map<String, Object> map = new HashMap<String,Object>();
		map.put("userId", userId);
		map.put("type", type);
		Integer total = 0;
		TblUser user = tblUserMapper.selectByPrimaryKey(userId);
		PageHelper.startPage(pageNumber,pageSize);
		List<TblUserPurseInfo> list = tblUserPurseInfoMapper.selectIntegral(map);
		PageInfo<TblUserPurseInfo> pageInfo = new PageInfo<>(list);
		if(type==2){
			total = user.getgUserIntegral().intValue();
		}else{
			total = user.getgUserGrow();
		}
		return new ReturnData(list,pageInfo.getPages(),(int)pageInfo.getTotal(),200,"积分明细(成长值明细)",total);
	}

	@Override
	public TblIntegralSet getDetailByType(Integer type) {
		// TODO Auto-generated method stub
		return tblIntegralSetMapper.selectByType(type);
	}

	@Override
	public int updateIntegral(TblIntegralSet integralSet) {
		// TODO Auto-generated method stub
		return tblIntegralSetMapper.updateByPrimaryKeySelective(integralSet);
	}

	@Override
	public int insertIntegral(TblIntegralSet integralSet) {
		// TODO Auto-generated method stub
		return tblIntegralSetMapper.insertSelective(integralSet);
	}

	@Override
	public ReturnData getIntegral() {
		// TODO Auto-generated method stub
		TblIntegralSet integralSet = tblIntegralSetMapper.selectByType(2);
		Double integral = integralSet.getIntegral()/integralSet.getMoney();
		return new ReturnData(integral,200,"1块钱兑换多少积分");
	}
}
